
package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.Date;

import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.service.listeners.ClientRegistrationListener;
import com.acme.bankapp.service.listeners.EmailNotificationListener;
import com.acme.bankapp.service.listeners.PrintClientListener;

public class Bank implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final int MAX_CLIENTS_COUNT = 10;
	private static final int MAX_LISTENERS_COUNT = 5;
	private Client[] clients = new Client[MAX_CLIENTS_COUNT];
	private ClientRegistrationListener[] listeners = 
				new ClientRegistrationListener[MAX_CLIENTS_COUNT];
	private int clientsCount;
	private int listenersCount;
	
	public Bank() {
		addListener(new EmailNotificationListener());
		addListener(new PrintClientListener());
		class DebugListener implements ClientRegistrationListener {
			@Override
			public void onClientAdded(Client client) {
				System.out.println(client + " " + new Date());
			}
		}
		addListener(new DebugListener());
	}
	
	private void addListener(ClientRegistrationListener listener) {
		if (listenersCount < MAX_LISTENERS_COUNT) {
			listeners[listenersCount] = listener;
			++listenersCount;
		}
	}
 
	public void addClient(Client client) {
		if (clientsCount < MAX_CLIENTS_COUNT) {
			clients[clientsCount] = client;
			clientsCount++;
			for (ClientRegistrationListener listener : listeners) {
				if (listener != null)
					listener.onClientAdded(client);
			}
		}
	}
	
	public Client getClient(int i) {
		if (clients == null)
			return null;
		if (clientsCount <= i)
			return null;
		return clients[i];
	}

	public Client[] getClients() {
		Client[] clients = new Client[clientsCount];
		System.arraycopy(this.clients, 0, clients, 0, clientsCount);
		return clients;
	}
}
